package org.maxgroundstation.simulation.service.log;

import java.util.Iterator;

import org.maxgroundstation.simulation.service.Service;
import org.maxgroundstation.simulation.service.ServiceCommunication;
import org.maxgroundstation.simulation.service.ServiceDataFrame;
import org.maxgroundstation.simulation.service.ServiceSubscriber;
import org.maxgroundstation.simulation.service.ServiceUtil;

/**
 * The log service.
 */
public class LogService extends Service {

	// Static members
	public static final String SERVICE_ID = ServiceUtil.getServiceID("log");
	
	/**
	 * Constructor
	 * @param comm the service communication.
	 */
	public LogService(ServiceCommunication comm) {
		// Use Service constructor.
		super(comm);
		
		name = "Log";
		description = "Returns log messages from robot when subscribed to.";
	}
	
	@Override
	public String getID() {
		return SERVICE_ID;
	}

	@Override
	public boolean isDefaultService() {
		return false;
	}

	@Override
	public void handleResponse(ServiceDataFrame dataFrame, int commType)
			throws Exception {
		// Do nothing.
	}

	@Override
	public void shutDown() {
		// TODO: implement
	}
	
	@Override
	public boolean isSubscribable() {
		return true;
	}
	
	/**
	 * Logs a message.
	 * @param message the log message.
	 */
	public void log(String message) {
		// Send log message to subscriber clients.
		Iterator<ServiceSubscriber> i = subscribers.iterator();
		while (i.hasNext()) {
			ServiceSubscriber subscriber = i.next();
			if (comm.getClientManager().checkClient(subscriber.getClientID())) {
				try {
					comm.sendServicePost(subscriber.getCommType(), getID(), subscriber.getClientID(), 
							message.getBytes());
				}
				catch (Exception e) {
					e.printStackTrace(System.err);
				}
			}
			else i.remove();
		}
	}
	
    /**
     * Logs an exception.
     * @param e the exception.
     */
    public void log(Exception e) {
    	// Send log message to subscriber clients.
		Iterator<ServiceSubscriber> i = subscribers.iterator();
		while (i.hasNext()) {
			ServiceSubscriber subscriber = i.next();
			if (comm.getClientManager().checkClient(subscriber.getClientID())) {
				try {
					comm.sendServicePost(subscriber.getCommType(), getID(), subscriber.getClientID(), 
							e.getMessage().getBytes());
				}
				catch (Exception e2) {
					e2.printStackTrace(System.err);
				}
			}
			else i.remove();
		}
    }
}